using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Task = System.Threading.Tasks.Task;

/****************************************************
// 功能：
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/2/21 15:14:57
*****************************************************/

public class TipsWindow : BaseWindow
{
    private Animation tipsAnimation;
    private Text tips;
    private long showTime;

    private readonly Queue<String> queue = new Queue<string>();
    private bool isTipsShow;

    private void Update()
    {
        lock (queue)
        {
            if (queue.Count > 0 && isTipsShow == false)
            {
                string str = queue.Dequeue();
                isTipsShow = true;
                SetTips(str); 
            }
        }
    }

    protected override void InitWindows()
    {
        base.InitWindows();
        tipsAnimation = transform.GetComponent<Animation>();
        tips = FindChildTransform(transform, "Text").GetComponent<Text>();
        //SetActive(tips, false);
        queue.Clear();
    }

    protected override void OnOpen(object arg)
    {
        base.OnOpen(arg);
        //ShowTips(arg as string);
        AddTips(arg as string);
    }

    public void AddTips(string str)
    {
        lock (queue)
        {
            queue.Enqueue(str);
        }
    }
    
    private void SetTips(string str)
    {
        SetActive(tips);
        SetText(tips, str);
        tips.transform.parent.GetComponent<RectTransform>().sizeDelta = new Vector2(88 + 36 * str.Length, 88);
        
        AnimationClip clip = tipsAnimation.GetClip("TipsShow");
        tipsAnimation.Play();
        // 延迟关闭激活状态
        StartCoroutine(AnimationPlayDone(clip.length, () =>
        {
            SetActive(tips, false);
            isTipsShow = false;
            ui.ClosePopUp(WindowName.Tips);
        }));
    }

    private IEnumerator AnimationPlayDone(float second, Action action)
    {
        yield return new WaitForSeconds(second);
        if (action != null)
        {
            action();
        }
        
    }

    async void ShowTips(string str)
    {
        SetText(tips, str);
        showTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
        tips.transform.parent.GetComponent<RectTransform>().sizeDelta = new Vector2(88 + 36 * str.Length, 88);
        
        // 2s后消失
        await Task.Delay(2000);
        if (DateTimeOffset.Now.ToUnixTimeMilliseconds() >= showTime + 2000)
        {
            ui.ClosePopUp(WindowName.Tips);
        }
    }
}
